package com.mercadoutils.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.Meli;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.listeners.SesionListener;
import com.mercadoutils.singletons.PoolConectionsSingleton;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;

@Controller
public class DeleteProductController {
	@RequestMapping("/deleteProductMU.html")
	 public String doRedirect(@RequestParam("json") String jsonIds,Model model) throws AuthorizationFailure, ServletException, SQLException
	 {
		JsonElement jelement = new JsonParser().parse(jsonIds); 
	    JsonObject  jobject = jelement.getAsJsonObject();
	    JsonArray jArray = jobject.getAsJsonArray("array");
	    Connection conexion = PoolConectionsSingleton.getConection();  
	    HttpSession session = SesionListener.getSession();
	    Statement st = conexion.createStatement();
        ResultSet rs;
	    for(int i=0;i<jArray.size();i++){
	    	jobject= jArray.get(i).getAsJsonObject();
	    	st.executeUpdate("update item set status='delete' where id="+jobject.get("id").toString());
	    }
	    return "redirect:/productListPendientes.html";
	 }
	
	@RequestMapping("/deleteProductML.html")
	 public String doRedirect2(Model model) throws AuthorizationFailure, ServletException, SQLException, MeliException, IOException
	 {
		
	
	    HttpSession session = SesionListener.getSession();
	    Meli m = (Meli) session.getAttribute("meli");
	    FluentStringsMap params = new FluentStringsMap();
	    params.add("access_token", m.getAccessToken());
	    m.put("/items/MLA482135092/status", params, "{\"status\":\"closed\"}");
	    Response r = m.put("/items/MLA482135092", params, "{\"status\":\"closed\"}");
	    System.out.println(r.getResponseBody().toString());
	    return "redirect:/productListPublicados.html";
	 }
	
	 

}
